package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 为了程序的健壮性 在后端进行判断 校验
        // 1、处理各种业务异常：
        //      地址溥为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            // 抛出业务异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //      购物车数据为空
        // 查询当前用户购物车数据
        Long userId = BaseContext.getCurrentId();   // 获取用户 id
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(userId)
                .build();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            // 抛出业务异常
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 2、向订单插入 1 条数据
        Orders orders = new Orders();
        // 属性拷贝
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        // 下单时间
        orders.setOrderTime(LocalDateTime.now());
        // 支付状态   未支付
        orders.setPayStatus(Orders.UN_PAID);
        // 订单状态   待付款
        orders.setStatus(Orders.PENDING_PAYMENT);
        // 订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));   // 设置为时间戳
        // 收货人 手机号 用户id
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);

        // 插入地址
        String address =
                addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail();
        orders.setAddress(address);

        // 插入数据
        orderMapper.insert(orders);

        // 3、向订单明细表插入 n 条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            // 封装成订单明细对象
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            // 设置订单明细关联的 订单 id
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        // 批量插入订单明细表数据
        orderDetailMapper.insertBatch(orderDetailList);

        // 4、清空当前用户的购物车数据
        shoppingCartMapper.deleteByUserId(userId);

        // 5、封装 VO 返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

/*
        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }
*/
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        // 更新支付成功后的数据库订单状态更新
        Integer payStatus = Orders.PAID;      // 已支付
        Integer status = Orders.TO_BE_CONFIRMED;   // 订单状态 待接单
        // 支付时间
        LocalDateTime checkoutTime = LocalDateTime.now();

        Orders orders = orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber());
        orders.setStatus(status);
        orders.setCheckoutTime(checkoutTime);
        orders.setPayStatus(payStatus);

        orderMapper.update(orders);

        // 通过 WebSocket 向客户端浏览器推送消息
        Map map = new HashMap();
        map.put("type", 1);  // 1 表示来单提醒 2 表示客户催单
        map.put("orderId", orders.getId());
        map.put("content", "订单号" + orders.getNumber());
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 历史订单查询
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult pageQuery(Integer pageNum, Integer pageSize, Integer status) {

        // 使用分页插件 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList<>();
        // 查询订单明细 并封装入OrderVo
        if (page != null && page.getTotal() > 0) {
            for (Orders orders: page) {
                Long ordersId = orders.getId();

                // 查询对应的订单明细
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrdersId(ordersId);

                // 创建VO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                list.add(orderVO);
            }
        }

        return new PageResult(page.getTotal(), list);
    }

    /**
     * 根据订单明细id 查询订单明细
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderDetailById(Long id) {

        // 根据订单id 查询订单明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrdersId(id);

        // 查询订单
        Orders orders = orderMapper.getById(id);

        // 封装所查询到的数据
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancelById(Long id) {

        Orders orders = orderMapper.getById(id);

        // 校验订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Integer status = orders.getStatus();

        // 判断订单状态
        // 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (status.equals(Orders.PENDING_PAYMENT) || status.equals(Orders.TO_BE_CONFIRMED)) {
            // 符合状态即可取消订单
            // 设置订单状态 已订单
            orders.setStatus(Orders.CANCELLED);
            // 设置订单 取消时间
            orders.setCancelTime(LocalDateTime.now());
            // 设置订单 取消原因
            orders.setCancelReason("用户取消");
            orderMapper.update(orders);
        } else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    @Transactional
    public void repetitionById(Long id) {

        // 获取订单明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrdersId(id);

        // 将获取到的订单数据和订单明细数据 重新封装到购物车中

        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            // 设置用户id
            shoppingCart.setUserId(BaseContext.getCurrentId());
            // 设置加入购车的时间
            shoppingCart.setCreateTime(LocalDateTime.now());
            // 插入购物车数据
            shoppingCartMapper.insert(shoppingCart);

        }

/*
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());
*/

    }

    @Override
    public PageResult conditionSearch(LocalDateTime beginTime, LocalDateTime endTime, String number, Integer pageNum, Integer pageSize, String phone, Integer status) {

        // 使用分页插件 设置分页
        PageHelper.startPage(pageNum, pageSize);

        // 进行查询 构建查询条件
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        // 插入条件
        ordersPageQueryDTO.setBeginTime(beginTime);     // 订单开始时间
        ordersPageQueryDTO.setEndTime(endTime);         // 订单结束时间
        ordersPageQueryDTO.setNumber(number);           // 订单号
        ordersPageQueryDTO.setPage(pageNum);
        ordersPageQueryDTO.setPageSize(pageSize);
        ordersPageQueryDTO.setPhone(phone);
        ordersPageQueryDTO.setStatus(status);           // 订单状态
        // ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList<>();
        // 查询订单明细 获取菜品信息
        if (page != null && page.getTotal() > 0) {
            for (Orders orders: page) {
                Long ordersId = orders.getId();

                // 查询订单明细
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrdersId(ordersId);
                // 获取菜品信息
                /*StringBuilder orderDishes = new StringBuilder();
                for (OrderDetail orderDetail : orderDetailList) {
                    orderDishes
                            .append(orderDetail.getName())
                            .append("*")
                            .append(orderDetail.getNumber())
                            .append("; ");
                }*/
                List<String> orderDishList = orderDetailList.stream().map(x -> {
                    return x.getName() + "*" + x.getNumber() + "; ";
                }).collect(Collectors.toList());

                String orderDishes = String.join("", orderDishList);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDishes(orderDishes);
                list.add(orderVO);

            }
        }

        return new PageResult(page.getTotal(), list);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO getStatistics() {

        // 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消

        // 获取带派送数量
        Integer confirmed = orderMapper.getCountByStatus(Orders.CONFIRMED);

        // 获取派送中数量
        Integer deliveryInProgress = orderMapper.getCountByStatus(Orders.DELIVERY_IN_PROGRESS);

        // 获取待接单数量
        Integer toBeConfirmed = orderMapper.getCountByStatus(Orders.TO_BE_CONFIRMED);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);

        orderMapper.update(orders);

    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {

        // 获取订单id
        Long orderId = ordersRejectionDTO.getId();
        // 查看订单状态
        Orders ordersDB = orderMapper.getById(orderId);

        // 判断订单是否存在  且状态是否符合要求
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = Orders.builder()
                .id(orderId)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())    // 传入取消时间
                .cancelReason(ordersRejectionDTO.getRejectionReason())      // 拒单原因传入
                .build();

        orderMapper.update(orders);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {

        // 获取订单id
        Long id = ordersCancelDTO.getId();
        // 查询订单是否存在
        Orders ordersDB = orderMapper.getById(id);
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 判断订单状态是否正确
        Integer status = ordersDB.getStatus();
        if (status == Orders.TO_BE_CONFIRMED || status == Orders.CANCELLED) {
            // 订单在 待接单 已取消的情况下 不可取消订单
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        } else {
            Orders orders = Orders.builder()
                    .id(id)
                    .status(Orders.CANCELLED)
                    .cancelReason(ordersCancelDTO.getCancelReason())
                    .cancelTime(LocalDateTime.now())
                    .build();
            orderMapper.update(orders);
        }

    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        // 查询订单是否存在
        Orders ordersDB = orderMapper.getById(id);
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 判断订单状态是否是 待派送
        if (!ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        } else {
            // 订单处于待派送
            Orders orders = Orders.builder()
                    .id(id)
                    .status(Orders.DELIVERY_IN_PROGRESS)
                    .build();
            orderMapper.update(orders);
        }

    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        // 查询订单是否存在
        Orders ordersDB = orderMapper.getById(id);
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 判断订单状态是否是 派送中
        if (!ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        } else {
            // 订单处于待派送
            Orders orders = Orders.builder()
                    .id(id)
                    .status(Orders.COMPLETED)
                    .deliveryTime(LocalDateTime.now())  // 设置送达时间
                    .build();
            orderMapper.update(orders);
        }
    }

    /**
     * 客户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders ordersDB = orderMapper.getById(id);
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 给浏览器发送消息

        Map map = new HashMap();
        map.put("type", 2);     // 1 表示来单提醒 2 表示客户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + ordersDB.getNumber());

        String json = JSON.toJSONString(map);

        // 通过WebSocket向客户端浏览器推送消息
        webSocketServer.sendToAllClient(json);

    }
}
